package com.cvmars.jianyou.utils;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by hehaifeng on 2018/8/17.
 */

public class DownloadApkThread extends Thread {


    String verUrl;

    String verName;

    Handler mHandler;

    boolean cancelUpdate = false;

    public static final int DOWNLOAD_FINISH = 0;

    public static final int DOWNLOAD_PROGRESS = 1;

    public static final int DOWNLOAD_ERROR = 2;

    public DownloadApkThread(Handler handler, String downloadUrl, String verName){

        this.verUrl = downloadUrl;

        this.verName = verName;

        this.mHandler = handler;

    }

    @Override
    public void run() {
        try {
            // 判断SD卡是否存在，并且是否具有读写权限
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 获得存储卡的路径

                String mSavePath = getYxkGuideDir("download");

                File savedir = new File(mSavePath);
                if (!savedir.exists()) {
                    savedir.mkdirs();
                }

                URL url = new URL(verUrl);
                // 创建连接
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.connect();
                // 获取文件大小
                int length = conn.getContentLength();
                // 创建输入流
                InputStream is = conn.getInputStream();

                File apkFile = new File(mSavePath, verName +".apk");
                FileOutputStream fos = new FileOutputStream(apkFile);
                int count = 0;
                // 缓存
                byte buf[] = new byte[1024];
                // 写入到文件中
                do {
                    int numread = is.read(buf);
                    count += numread;
                    // 计算进度条位置
                    int progress = (int) (((float) count / length) * 100);

                    Message message = Message.obtain();
                    message.what = DOWNLOAD_PROGRESS;
                    message.arg1 = progress;
                    // 更新进度
                    mHandler.sendMessage(message);
                    if (numread <= 0) {
                        // 下载完成
                        Message messageFinish = Message.obtain();
                        messageFinish.what = DOWNLOAD_FINISH;
                        messageFinish.obj = mSavePath + verName +".apk";
                        mHandler.sendMessage(messageFinish);
                        break;
                    }
                    // 写入文件
                    fos.write(buf, 0, numread);
                } while (!cancelUpdate);// 点击取消就停止下载.
                fos.close();
                is.close();
            }
        } catch (MalformedURLException e) {
            mHandler.sendEmptyMessage(DOWNLOAD_ERROR);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(DOWNLOAD_ERROR);
        }
    }


    // 获取app存放存储卡目录
    public String getYxkGuideDir(String subDir) {
        String sdpath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();

        File savedirs = new File(sdpath+ "/chat/");
        if (!savedirs.exists()) {
            savedirs.mkdirs();
        }
        if (subDir != null) {
            sdpath = sdpath + "/chat/" + subDir + "/";
        } else {
            sdpath = sdpath + "/chat/";
        }
        File savedir = new File(sdpath);
        if (!savedir.exists()) {
            savedir.mkdirs();
        }
        return sdpath;
    }

    /**
     *
     * 取消下载
     */
    public void onCancel(){

        this.cancelUpdate = true;
    }
}
